<?php

class  Basket implements \Iterator
{
	private $fruits = array(
		'apple',
		'banna',
		'pear',
		'orange',
		'watermelon'
	);
	//现在的位置
	private $posistion = 0;

	/**
	 * 遍历到现在的值是什么
	 */
	public function current()
	{
		return $this->fruits[$this->posistion];
	}

	/**
	 * 遍历到现在的key是什么
	 */
	public function key()
	{
		return $this->posistion;
	}

	/**
	 * 遍历下一个
	 */
	public function next()
	{
		++$this->posistion;
	}

	/**
	 * foreach变量开始时自动调用
	 */
	public function rewind()
	{
		$this->posistion = 0;
	}

	/**
	 * 判断现在的key是否是合理，返回true则遍历，false则停止遍历
	 */
	public function valid()
	{
		if ($this->posistion < count($this->fruits)) return true;
		return false;
	}
}


$basket = new Basket();
foreach ($basket as $key => $fruit)
{
	echo $key, '--', $fruit, "\n";
}
//也可用下面的遍历方式，效果一样
while ($basket->valid())
{
	echo $basket->key(), '--', $basket->current(), "\n";
	$basket->next();
}